import api from '../../api/index';
import { sdk } from '../../config/sdk';

Page({
  data: {
    terms: ['第一学期', '第二学期'],
    loading: true
  },

  onLoad: function (options) {
    this.getDate()
  },

  // 获取日期
  getDate() {
    const yIndex = new Date().getFullYear();
    const mIndex = new Date().getMonth() + 1;
    var years = [];
    var year = yIndex;
    var defaultYear = 0;
    var term = 1;
    var defaultTerm = 0;
    for (let y = yIndex - 3; y <= yIndex + 1; y++) {
      var yobj = {};
      yobj.key = `${y}-${y + 1} 年`;
      yobj.val = y;
      years.push(yobj);
    }
    if (mIndex >= 9 || mIndex <= 2) {
      var arr = [];
      years.forEach(item => { arr.push(item.val) });
      defaultYear = arr.indexOf(yIndex - 1);
      term = 1;
      defaultTerm = 0;
    }
    if (mIndex >= 3 || mIndex <= 8) {
      var arr = [];
      years.forEach(item => { arr.push(item.val) });
      defaultYear = arr.indexOf(yIndex - 1);
      year = yIndex - 1;
      term = 2;
      defaultTerm = 1;
    }
    this.setData({ years, year, defaultYear, term, defaultTerm });
    this.getScore()
  },

  // 年份选择
  YearChange(e) {
    const { years } = this.data;
    const index = parseInt(e.detail.value);
    this.setData({
      year: years[index].val,
      defaultYear: index
    });
  },

  // 学期选择
  TermChange(e) {
    const index = parseInt(e.detail.value);
    this.setData({
      term: index == 0 ? 1 : 2,
      defaultTerm: index
    });
  },

  // 请求数据
  async getScore() {
    const that = this;
    const { year, term } = this.data;
    const { code, message, data } = await sdk.request({ url: api.getScore, data: { year, term } });
    if (code != 1000) return this.$error(message);;
    this.setData({ 
      score: data, 
      loading: false,
      animation: true 
    });
    const timer = setTimeout(function () {
      that.setData({ 
        animation: false 
      });
      clearTimeout(timer);
    }, 1000);
  }
})